using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
namespace Net35.Xrm.Sdk
{
	public sealed class CallerImpersonationScope : IDisposable
	{
		private bool _disposed;
		private System.ServiceModel.OperationContextScope scope;
		public CallerImpersonationScope(IOrganizationService service, Guid callerId)
		{
			System.ServiceModel.Channels.MessageHeader header = System.ServiceModel.Channels.MessageHeader.CreateHeader("CallerId", "http://schemas.microsoft.com/xrm/2011/Contracts", callerId);
			System.ServiceModel.IContextChannel channel = (System.ServiceModel.IContextChannel)service;
			this.scope = new System.ServiceModel.OperationContextScope(channel);
			System.ServiceModel.OperationContext.Current.OutgoingMessageHeaders.Add(header);
		}
		public void Dispose()
		{
			if (this._disposed)
			{
				return;
			}
			if (System.ServiceModel.OperationContext.Current != null)
			{
				System.ServiceModel.OperationContext.Current.OutgoingMessageHeaders.RemoveAll("CallerId", "http://schemas.microsoft.com/xrm/2011/Contracts");
				if (this.scope != null)
				{
					this.scope.Dispose();
				}
			}
			this._disposed = true;
		}
	}
}
